<?php

namespace app\common\model\Subject;

use think\Model;
use think\model\Collection;
use app\common\model\Subject\Teacher\Teacher;
use traits\model\SoftDelete;

class Subject extends Model
{
    use SoftDelete;
    // 表名
    protected $name = 'subject';
    // 忽略数据表不存在的字段
    protected $field = true;
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    //禁止写入时间字段
    protected $updateTime = false;
    // 软删除的字段
    protected $deleteTime = 'deletetime';
    // 设置返回的结果类型
    protected $resultSetType = 'collection';
    // 追加属性
    protected $append = [
        'likes_num',
        'thumbs_text',
        'orders_num',
        'category',
        'teacher',
        'date',
        'chapters',
        'name',
    ];
    public function getLikesNumAttr($value,$data){
        if(!isset($data["likes"])){
            return 0;
        }
        return $data["likes"]?count(explode(',',$data['likes'])):0;
    }
    public function getThumbsTextAttr($value,$data){
        if(!isset($data['thumbs'])){
            return;
        }
        $sujectDefaultImg = is_file(ROOT_PATH.'public'.config('site.sujectDefaultImg'))?config('site.sujectDefaultImg'):'/assets/home/images/sujectDefaultImg.png';
        return is_file(ROOT_PATH.'public'.$data['thumbs'])?$data['thumbs']:$sujectDefaultImg;
    }
    public function getOrdersNumAttr(){
        return $this->hasMany('order','subid')->count();
    }
    public function getCategoryAttr(){
        return $this->hasOne('category','id','cateid')->select()->toArray()[0];
    }
    public function getTeacherAttr($value,$data){
        // $teacher = $this->hasOne('app\common\model\Subject\Teacher\Teacher','id','teacherid')
        //                 ->field('id,name,avatar,content,job,createtime')
        //                 ->select()
        //                 ->toArray();
        // return $data['teacherid'];
        $teacher = $this->hasOne('app\common\model\Subject\Teacher\Teacher','id','teacherid')->find();
        return $teacher;
    }
    public function getDateAttr($value,$data){
        if(!isset($data["createtime"])){
            return;
        }
        return date('Y-m-d',$data["createtime"]);
    }
    public function getChaptersAttr($value,$data){
        if(!isset($data['id']))return;
        $chapters = Chapter::field('id,title,createtime')->where('subid',$data['id'])->select()->toArray();
        return $chapters;
    }
    public function teacher()
    {
        return $this->belongsTo(Teacher::class,'teacherid','id',[],'left')->setEagerlyType(0);
    }
    public function category()
    {
        return $this->belongsTo(Category::class,'cateid','id',[],'left')->setEagerlyType(0);
    }
    public function getNameAttr($value,$data){
        return isset($data['title'])?$data['title']:'';
    }
}
